package com.tax.common.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Map;

public class SpringUtils {

    public static Object getBean(HttpServletRequest request, String serviceName) {
        ServletContext servletContext = request.getSession().getServletContext();
        AbstractApplicationContext wac = (AbstractApplicationContext) WebApplicationContextUtils.getWebApplicationContext(servletContext);
        return wac.getBean(serviceName);
    }

    public static AbstractApplicationContext getAbstractApplicationContext(HttpServletRequest request) {
        ServletContext servletContext = request.getSession().getServletContext();
        AbstractApplicationContext wac = (AbstractApplicationContext) WebApplicationContextUtils.getWebApplicationContext(servletContext);
        return wac;
    }

    public static Map<String,Object> getRequestBody(HttpServletRequest request) throws IOException {
        if ("POST".equalsIgnoreCase(request.getMethod())) {
            StringBuffer data = new StringBuffer();
            String line = null;
            BufferedReader reader = null;
            reader = request.getReader();
            while (null != (line = reader.readLine())) {
                data.append(line);
            }
            if (StringUtils.isNotBlank(data)) {
                return JSONObject.parseObject(data.toString(),Map.class);
            }
        }
        return null;
    }

}

